﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MeTalker.Window.SDK.Core;
using MeTalker.SDK.Core;
using System.Threading;

namespace MeTalker.Aide
{
    internal static class WangHepler
    {
       internal static void Send(IntPtr mainhWnd, IntPtr hWnd, string msg, bool flag)
        {
            try
            {
                EndSend(hWnd, msg, flag);
                for (int i = 0; i < 10; i++)
                {
                    if (mainhWnd == WindowControl.GetForegroundWindow())
                    {
                        break;
                    }
                    WindowControl.SetForegroundWindow(hWnd);
                    Thread.Sleep(5);
                }
                KeysetControl.SendMessage(hWnd, 7, 0, 0);
                Thread.Sleep(10);
            }
            catch
            {
            }
        }

        static void SendMessage(IntPtr hWnd, string msg)
        {
            if (hWnd != IntPtr.Zero)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(msg);
                KeysetControl.SendMessage(hWnd, KeysetControl.WM_SETTEXT, 0, builder);
            }
        }

      internal  static string EqualsMsg(IntPtr hWnd)
        {
            if (hWnd == IntPtr.Zero)
            {
                return null;
            }
            StringBuilder builder = new StringBuilder(0x800);
            KeysetControl.SendMessage(hWnd, KeysetControl.WM_GETTEXT, builder.Capacity, builder);
            return builder.ToString();
        }

        static void EndSend(IntPtr hWnd, string msg, bool flag)
        {
            if (hWnd != IntPtr.Zero)
            {
                try
                {
                    SendMessage(hWnd, msg);
                    for (int i = 0; i < 10; i++)
                    {
                        if (!(EqualsMsg(hWnd) != msg))
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep(10);
                    }
                    if (flag)
                    {
                        KeysetControl.SendMessage(hWnd, 0xb1, 0, -1);
                    }
                    else
                    {
                        KeysetControl.SendMessage(hWnd, 0xb1, -1, -1);
                    }
                }
                catch
                {
                }
            }
        }
    }
}